<template>
  <div class="flex flex-col h-full">
    <div class="flex-1 overflow-y-scroll table-wrap">
      <a-card class="w-full min-h-full mb-2">
        <div class="title flex items-center">
          <div>最终处方</div>
          <a-button type="primary" class="flex items-center justify-center ml-6 w-7 py-0 h-7 px-0" @click="getFinalCheckInfo(true)">
            <sync-outlined :style="{ fontSize: '18px' }" />
          </a-button>
          <img src="../../../../assets/icons/yanDoctor.png" alt="" class="ml-14" style="width: 32px" />
          <span class="ml-1 flex items-center"
            >验光师：
            <SelectTable
              v-if="isEditChkEmpId"
              v-model:value="finialCheckInfo.chkEmpName"
              type="员工"
              :table-width="720"
              placeholder="请选择"
              class="h-8 w-24"
              @select="
                (event) => {
                  finialCheckInfo.chkEmpName = event.empName
                  finialCheckInfo.chkEmpId = event.empId
                  onConfirmEditPre()
                }
              "
            />
            <span v-else>{{ finialCheckInfo.chkEmpName ? finialCheckInfo.chkEmpName : '-' }}</span>
            <a-tooltip>
              <template #title>修改验光师</template>
              <img src="../../../../assets/images/edit.png" class="w-6 h-6 cursor-pointer ml-2" alt="" @click="tranEditEmp()" />
            </a-tooltip>
          </span>
          <span v-if="isEditChkTime" class="ml-4"
            >验光时间：
            <a-date-picker
              v-model:value="finialCheckInfo.updateTime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
              placeholder="请选择验光时间"
              @ok="onConfirmEditPreTime"
          /></span>
          <span v-else class="ml-4"
            >验光时间： {{ finialCheckInfo.updateTime ? finialCheckInfo.updateTime : '-'
            }}<a-tooltip>
              <template #title>修改验光时间</template>
              <img src="../../../../assets/images/edit.png" class="w-6 h-6 cursor-pointer ml-2" alt="" @click="tranEditTime()" /> </a-tooltip
          ></span>
          <div class="flex-1 flex justify-end">
            <a-button v-if="isEditPreTable" type="primary" size="small" class="mr-2" @click="onConfirmEditPre()">确认修改</a-button>
            <a-tooltip v-else>
              <template #title>修改最终处方</template>
              <img src="../../../../assets/images/edit.png" class="w-6 h-6 cursor-pointer mr-4" alt="" @click="tranEditPreTable()" />
            </a-tooltip>
            <a-tooltip v-if="isShowPreTable">
              <template #title>折叠</template>
              <img src="../../../../assets/images/up.png" class="w-6 h-6 cursor-pointer" alt="" @click="tranPreTable(false)" />
            </a-tooltip>
            <a-tooltip v-else>
              <template #title>展开</template>
              <img src="../../../../assets/images/down.png" class="w-6 h-6 cursor-pointer" alt="" @click="tranPreTable(true)" />
            </a-tooltip>
          </div>
        </div>
        <PreTable
          v-if="isShowPreTable"
          ref="preTable"
          :is-edit="isEditPreTable"
          :resource-data="finialCheckInfo"
          :loading="preLoading"
          @success="onSuccessPreTable"
        />
        <div v-for="(item, idx) in saleForm" :key="idx" class="mb-4 mt-2 relative">
          <img v-if="item.payStatus" src="../../../../assets/images/al-charge-icon.png" class="w-10 h-10 absolute top-1 left-1" alt="" />
          <div class="flex items-center form-header py-2 rounded-t-lg">
            <a-form :model="item.doSaveOoOpticianRecordRequest" :colon="false" class="form-style-flex ml-8 min-h-20 items-center">
              <a-form-item label="销售单" class="w-60 mb-0 mt-2">
                <p class="mb-0 ml-2 font-bold text-black">{{ item.doSaveOoOpticianRecordRequest?.id }}</p>
              </a-form-item>
              <a-form-item label="" class="w-40 mb-0 mr-3 mt-2">
                <a-radio-group
                  :value="item.doSaveOoOpticianRecordRequest.longOrShort"
                  :disabled="item.doSaveOoOpticianRecordRequest.longShortDisabled || item.opticianStatus"
                  @change="(e) => onLongShortChange(e, item)"
                >
                  <a-radio :value="'1'">远用</a-radio>
                  <a-radio :value="'2'">近用</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="经手人" class="w-36 mb-0 mr-3 mt-2">
                <SelectTable
                  v-model:value="item.doSaveOoOpticianRecordRequest.handlerName"
                  :disabled="item.opticianStatus"
                  type="员工"
                  placeholder="请选择"
                  @select="
                    (event) => {
                      item.doSaveOoOpticianRecordRequest.handlerName = event.empName
                      item.doSaveOoOpticianRecordRequest.handlerId = event.empId
                    }
                  "
                />
              </a-form-item>
              <a-form-item label="推荐医生" class="w-36 mb-0 mr-3 mt-2">
                <SelectTable
                  v-model:value="item.doSaveOoOpticianRecordRequest.doctorName"
                  :disabled="item.opticianStatus"
                  type="员工"
                  :table-width="720"
                  placeholder="请选择"
                  @select="
                    (event) => {
                      item.doSaveOoOpticianRecordRequest.doctorName = event.empName
                      item.doSaveOoOpticianRecordRequest.doctorId = event.empId
                    }
                  "
                />
              </a-form-item>
              <a-form-item label="配镜师" class="w-36 mb-0 mr-3 mt-2">
                <SelectTable
                  v-model:value="item.doSaveOoOpticianRecordRequest.opticianDoctorName"
                  :disabled="item.opticianStatus"
                  type="员工"
                  :table-width="720"
                  placeholder="请选择"
                  @select="
                    (event) => {
                      item.doSaveOoOpticianRecordRequest.opticianDoctorName = event.empName
                      item.doSaveOoOpticianRecordRequest.opticianDoctorId = event.empId
                    }
                  "
                />
              </a-form-item>
              <a-form-item label="开单人" class="w-36 mb-0 mr-3 mt-2">
                <SelectTable
                  v-model:value="item.doSaveOoOpticianRecordRequest.billEmpName"
                  :disabled="item.opticianStatus"
                  type="员工"
                  :table-width="720"
                  placeholder="请选择"
                  @select="
                    (event) => {
                      item.doSaveOoOpticianRecordRequest.billEmpName = event.empName
                      item.doSaveOoOpticianRecordRequest.billEmpId = event.empId
                    }
                  "
                />
              </a-form-item>
              <a-form-item label="预收款" class="w-48 mb-0 mr-3 mt-2 flex">
                <img
                  v-if="item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '1'"
                  src="../../../../assets/images/al-charge-icon.png"
                  class="w-10 h-10 absolute -left-10 -top-1"
                  alt=""
                />
                <a-switch
                  v-model:checked="item.downPayOpen"
                  :disabled="
                    item.opticianStatus ||
                    item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '1' ||
                    item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '2'
                  "
                  @change="(e) => downPaySwitchChange(e, item)"
                />
                <a-input
                  v-if="item.downPayOpen"
                  v-model:value="item.doSaveOoOpticianRecordRequest.downPaymentAmount"
                  :disabled="
                    item.opticianStatus ||
                    item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '1' ||
                    item.doSaveOoOpticianRecordRequest.chargeDepositStatus === '2'
                  "
                  class="w-6/12 ml-3"
                  placeholder="请输入金额"
                  @blur="onBlurInputDownPay(item)"
                />
              </a-form-item>
              <a-form-item label="预计取镜" class="w-48 mb-0 mr-3 mt-2">
                <a-date-picker v-model:value="item.doSaveOoOpticianRecordRequest.takeTime" value-format="YYYY-MM-DD" @change="onChangeTime(item, $event)" />
              </a-form-item>
              <a-form-item label="备注" class="w-1/2 mb-0 mt-2">
                <a-textarea v-model:value="item.doSaveOoOpticianRecordRequest.memo" :disabled="item.opticianStatus" placeholder="请输入" :rows="1" />
              </a-form-item>
            </a-form>
            <div class="flex items-center justify-end flex-1 btn-box">
              <a-button type="primary" class="ml-4" :disabled="item.opticianStatus" @click="onClickDiscounts(item, 1)">批量打折</a-button>
              <a-button class="ml-4" :disabled="!item.opticianStatus" @click="printSale(item)">打印</a-button>
              <BaseButton
                class="flex items-center justify-center ml-4 mr-2 px-1 w-7 h-7"
                :disabled="item.opticianStatus || item.payStatus"
                confirm-text="确认删除？"
                danger
                @click="deleteCheckInfo(item, idx)"
              >
                <delete-outlined :style="{ fontSize: '16px' }" />
              </BaseButton>
            </div>
          </div>
          <div class="border px-4 py-4">
            <BaseTable
              :loading="loading"
              column-code="000184"
              :scroll="{ x: 1700 }"
              row-key="id"
              :data-source="item.list"
              bordered
              :row-class-name="getRowClass"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.dataIndex == 'isOutside'">
                  <a-switch
                    v-model:checked="record.isOutside"
                    :disabled="item.opticianStatus || record.storeType === '1'"
                    :checked-value="'1'"
                    :un-checked-value="'0'"
                    @change="(e) => onSwitchChange(e, record, item)"
                  />
                </template>
                <!--眼别   1：左眼 2：右眼 3：其他 -->
                <template v-if="column.dataIndex == 'eyesType'">
                  <span v-if="record.eyesType == 1">左眼</span>
                  <span v-else-if="record.eyesType == 2">右眼</span>
                  <span v-else-if="record.eyesType == 3">其他</span>
                  <span v-else>/</span>
                </template>
                <!-- 类别 -->
                <template v-if="column.dataIndex == 'payItemType'">
                  <span v-if="record.payItemType == 60">镜架费</span>
                  <span v-if="record.payItemType == 61 || record.payItemType == 62 || record.payItemType == 63">镜片费</span>
                  <span v-if="record.payItemType == 65 || record.payItemType == 64">视光其他</span>
                </template>
                <template v-if="column.dataIndex == 'search'">
                  <EditCell title="检索" :disabled="item.opticianStatus || record.status === '2'" class="flex justify-center items-center">
                    <SearchOutlined @click="openSearchModal(item, record, idx, index)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex == 'payItemName'">
                  <EditCell title="名称" :disabled="item.opticianStatus || record.status === '2'">
                    <SelectMedicineCustom
                      v-if="record.payItemType == 60"
                      :value="record"
                      type="视光商品镜架"
                      :insure-status="1"
                      :table-width="780"
                      :auto-focus="false"
                      :search-params="{ xmlbs: formatLb(record.payItemType) }"
                      @select="getSkuData(item, record, $event, false, idx, index)"
                    />
                    <div v-if="record.payItemType == 61 || record.payItemType == 62 || record.payItemType == 63" class="h-full">
                      <SelectMedicineCustom
                        v-if="judgeSelect(item)"
                        :value="record"
                        type="视光商品镜片"
                        :insure-status="1"
                        :table-width="780"
                        is-verify-select
                        :auto-focus="record.autoFocus"
                        :search-params="{
                          xmlbs: formatLb(record.payItemType),
                          astigmatism: formatAstigmatism(item, record),
                          diopter: formatDiopter(item, record)
                        }"
                        @select="getSkuData(item, record, $event, false, idx, index)"
                      />
                      <div v-else class="h-full">
                        <a-input placeholder="请选择" @focus="onJudgeFocus(item)" />
                      </div>
                    </div>
                    <SelectMedicineCustom
                      v-if="record.payItemType == 65 || record.payItemType == 64"
                      :value="record"
                      type="视光商品其它"
                      :insure-status="1"
                      :table-width="630"
                      :auto-focus="record.autoFocus"
                      :search-params="{ xmlbs: formatLb(record.payItemType) }"
                      @select="getSkuData(item, record, $event, false, idx, index)"
                    />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex == 'num'">
                  <EditCell title="数量" :disabled="item.opticianStatus">
                    <a-input v-model:value="record.num" placeholder="请输入" :suffix="record.unit" @blur="onBlurNum(item, record, $event)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex == 'memo'">
                  <EditCell title="备注" :disabled="item.opticianStatus">
                    <a-input v-model:value="record.memo" placeholder="请输入" @blur="onBlurInput(item, record, $event)" />
                  </EditCell>
                </template>
                <template v-if="column.dataIndex == 'payStatus'">
                  <!-- 0：未缴费 1：已缴费 -->
                  <span v-if="record.payStatus === '1'">已缴费</span>
                  <span v-else-if="record.payStatus === '0'" style="color: rgb(0, 112, 240)">未缴费</span>
                  <span v-else>-</span>
                </template>
                <template v-if="column.dataIndex == 'status'">
                  <!-- 1：正常 2：待退费 3：已退费-->
                  <span v-if="record.status === '1'">正常</span>
                  <span v-else-if="record.status === '2'" style="color: #d9001b">待退费</span>
                  <span v-else-if="record.status === '3'" style="color: #d9001b">已退费</span>
                  <span v-else>-</span>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <BaseButton
                    v-if="record.status == '1'"
                    confirm-text="确认作废？"
                    type="text"
                    :disabled="item.opticianStatus"
                    danger
                    size="small"
                    @click="onDelete(record, idx, index)"
                    >作废</BaseButton
                  >
                  <BaseButton v-if="record.status == '2'" confirm-text="确认作废？" type="text" disabled danger size="small">已作废</BaseButton>
                  <a-button type="link" size="small" :disabled="item.opticianStatus" @click="onClickDiscounts(item, record)"> 打折 </a-button>
                </template>
              </template>
            </BaseTable>
            <div class="flex justify-center mt-4">
              <a-button :disabled="item.opticianStatus" @click="AddTableItem(item)"><plus-outlined />新增一行</a-button>
              <!-- 方式1  debounce -->
              <BaseButton
                type="primary"
                class="ml-4"
                :debounce="500"
                :loading="saveBtnLoading"
                :disabled="item.opticianStatus"
                @click="saveTableData(saleForm[idx])"
              >
                保存
              </BaseButton>
              <a-button v-if="item.opticianStatus" :disabled="item.payStatus" type="primary" class="ml-4" @click="cancelSaveAllSale(item)">撤销确认</a-button>
              <a-button v-else type="primary" class="ml-4" :disabled="item.opticianStatus" @click="saveAllSale(item)">确认开单</a-button>
            </div>
            <CouponCardOptician
              v-if="item.doSaveOoOpticianRecordRequest.id"
              :key="idx"
              :br-id="selectedItem.brId"
              :medical-price="amountNum.payAmount"
              :vip-card-input-disabled="true"
              :all-data="saleForm"
              :select-data="item"
              :ticket-data="item.opticianStatus ? item.doSaveOoOpticianRecordRequest.hykxx?.kqxx : ticketData"
              :vip-card-data="item.opticianStatus ? [item.doSaveOoOpticianRecordRequest.hykxx?.hyxx] : vipCardData"
              @success="(e) => onSuccessCoupon(e, item)"
            />
            <p class="mb-0 text-right">
              实收金额：<span class="text-red-500 font-bold">￥{{ formatAmount(item.doSaveOoOpticianRecordRequest.orderAmount) }}</span>
            </p>
          </div>
        </div>
      </a-card>
    </div>
    <div v-if="pageOne === '0'" class="h-72 mb-2">
      <a-card class="mt-2">
        <BaseTitle title="优惠合计" class="!mb-0">
          <p class="mb-0">
            优惠合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.discountAmount) }}</span>
          </p>
        </BaseTitle>
      </a-card>
      <a-card class="mt-2">
        <BaseTitle title="应收合计" class="!mb-0">
          <p class="mb-0">
            应收合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.totalAmount) }}</span>
          </p>
        </BaseTitle>
      </a-card>
      <a-card class="mt-2">
        <BaseTitle title="实收合计" class="!mb-0">
          <p class="mb-0">
            实收合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.payAmount) }}</span>
          </p>
        </BaseTitle>
      </a-card>
      <a-card class="mt-2">
        <div class="flex justify-end">
          <a-button @click="AddSaleBill">新增销售单</a-button>
        </div>
      </a-card>
    </div>
    <a-card v-else class="h-32 mt-2">
      <div class="flex justify-end items-center">
        <p class="mb-0 mr-8">
          应收合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.totalAmount) }}</span>
        </p>
        <p class="mb-0 mr-8">
          优惠合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.discountAmount) }}</span>
        </p>
        <p class="mb-0 mr-20">
          实收合计：<span class="text-red-500 font-bold">￥{{ formatAmount(amountNum.payAmount) }}</span>
        </p>
        <a-button @click="AddSaleBill">新增销售单</a-button>
      </div>
    </a-card>
    <DiscountsOne v-model:open="discountsOneOpen" :row-data="projectRow" @success="onDiscountsSuccess" />
    <DiscountsMany v-model:open="discountsManyOpen" :discounts-data="projectItem" @success="onDiscountsSuccess" />
    <GlassesFrame v-model:open="glassesFrameSearch" :row-data="recordItem" :form-item="formItem" @select="onSelectSearch" />
    <Lens v-model:open="LensSearch" :row-data="recordItem" :form-item="formItem" @select="onSelectSearch" />
    <OpticianOther v-model:open="OtherSearch" :row-data="recordItem" :form-item="formItem" @select="onSelectSearch" />
  </div>
</template>

<script setup>
import { ref, createVNode } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { Modal } from 'ant-design-vue'
import { SyncOutlined, DeleteOutlined, PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { SearchOutlined } from '@ant-design/icons-vue'
import { formatAmount } from '@/utils/format.js'
import { getSystemConfig } from '@/utils/systemConfig'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'
import userStore from '@/store/user'
import CouponCardOptician from '@/components/CouponCard/CouponCardOptician'
import PreTable from '../components/PreTable'
import DiscountsMany from '../components/DiscountsMany'
import SelectMedicineCustom from '../components/SelectMedicineCustom'
import GlassesFrame from '../components/Glasses-frame'
import Lens from '../components/Lens'
import OpticianOther from '../components/Optician-other'
import DiscountsOne from '../components/DiscountsOne'
import userOpticianStore from '../store'

// 镜架 60  设备 64  其他商品 65   镜片 61  隐形眼镜 62  角塑 63
const store = userOpticianStore()
const loading = ref(false)
const pageOne = ref('0')
// const prescriptionMode = ref('0')
const timer = ref(null)
const selectedItem = ref({})
const finialCheckInfo = ref({})
const preLoading = ref(false)
const discountsOneOpen = ref(false)
const discountsManyOpen = ref(false)
const projectRow = ref({})
const projectItem = ref({})
const amountNum = ref({
  discountAmount: 0,
  payAmount: 0,
  totalAmount: 0
})
const isShowPreTable = ref(true)
const isEditPreTable = ref(false)
const isEditChkEmpId = ref(false)
const isEditChkTime = ref(false)
const preTable = ref()
const glassesFrameSearch = ref(false)
const LensSearch = ref(false)
const OtherSearch = ref(false)
const formItem = ref({})
const recordItem = ref({})
const opticianStatus = ref(false) //true 有已开单数据
const { empId, empName } = userStore()
const saleBankForm = ref({
  isNew: true,
  downPayOpen: false,
  opticianStatus: false,
  payStatus: false,
  doSaveOoOpticianRecordRequest: {
    id: '',
    takeTime: null,
    brId: selectedItem.value.brId,
    handlerName: getSystemConfig('HOSPITAL_ORGNIZATION_CODE') === 'MAIP7BF56' ? '' : empName,
    handlerId: getSystemConfig('HOSPITAL_ORGNIZATION_CODE') === 'MAIP7BF56' ? '' : empId,
    opticianDoctorId: '',
    billEmpId: getSystemConfig('HOSPITAL_ORGNIZATION_CODE') === 'MAIP7BF56' ? '' : empId,
    billEmpName: getSystemConfig('HOSPITAL_ORGNIZATION_CODE') === 'MAIP7BF56' ? '' : empName,
    longOrShort: '' //1：远用 2：近用
  },
  // 60：镜架 61：镜片 65：其他商品
  list: [
    {
      isNew: true,
      autoFocus: false,
      eyesType: '',
      isOutside: '0',
      payStatus: '0',
      payItemType: '60',
      adviceTime: dayjs().format('YYYY-MM-DD hh:mm:ss')
    },
    {
      isNew: true,
      autoFocus: false,
      eyesType: '2',
      isOutside: '0',
      payStatus: '0',
      payItemType: '61',
      adviceTime: dayjs().format('YYYY-MM-DD hh:mm:ss')
    },
    {
      isNew: true,
      autoFocus: false,
      eyesType: '1',
      isOutside: '0',
      payStatus: '0',
      payItemType: '61',
      adviceTime: dayjs().format('YYYY-MM-DD hh:mm:ss')
    }
  ]
})
const saleForm = ref([])
const onChangeTime = (item, e) => {
  if (item.doSaveOoOpticianRecordRequest.id) saveGetLensDate(item.doSaveOoOpticianRecordRequest.id, e)
}
const saveGetLensDate = async (id, e) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doSaveTakeTime', {
    id,
    takeTime: e
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
}
const saveBtnLoading = ref(false)
const saveTableData = async (item) => {
  item.doSaveOoOpticianRecordRequest.brId = selectedItem.value.brId
  item.doSaveOoOpticianRecordRequest.ooLsh = selectedItem.value.jzbh
  item.doSaveOoOpticianRecordRequest.ooFinalCheckId = finialCheckInfo.value.id
  const flag = item.list.some((it) => {
    return it.payItemName && it.num
  })
  if (!flag) return message.error('请输入完整名称或数量信息')
  // 只要有一项完整输入名称和数量即可
  item.list = item.list.filter((it) => {
    return it.payItemName && it.num
  })
  saveBtnLoading.value = true
  const { code, msg } = await post('/optometry/ooadolescentcheck/doSaveOoOpticianRecord', {
    ...item
  })
  if (code !== 0) {
    saveBtnLoading.value = false
    return message.error(msg)
  }
  message.success(msg)
  queryList()
  getAmount()
}
// 确认开单
const saveAllSale = async (item) => {
  if (item.isNew) return message.error('请先保存销售单')
  if (!item.doSaveOoOpticianRecordRequest?.id) return message.error('请先保存销售单')
  const { code, msg } = await post('/optometry/ooadolescentcheck/DoComfirmOoOpticianRecord', {
    ooLsh: selectedItem.value.jzbh,
    id: item.doSaveOoOpticianRecordRequest?.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  queryList()
}
// 撤销确认开单
const cancelSaveAllSale = async (item) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/DoUnComfirmOoOpticianRecord', {
    ooLsh: selectedItem.value.jzbh,
    id: item.doSaveOoOpticianRecordRequest?.id
  })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  queryList()
}
const onDiscountsSuccess = async (params) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doDiscount', {
    hjje: params.hjje,
    id: params.saleId,
    jsje: params.jsje,
    ooLsh: selectedItem.value.jzbh,
    pwd: params.pwd,
    pzr: params.pzr,
    spids: params.spids,
    zkl: params.zkl
  })
  if (code !== 0) return message.error(msg)
  discountsOneOpen.value = false
  discountsManyOpen.value = false
  message.success(msg)
  queryList()
  getAmount()
}
const getAmount = async () => {
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoOpticianRecordListAmountSG', {
    ooLsh: selectedItem.value.jzbh
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    amountNum.value = data
  } else {
    amountNum.value = {
      discountAmount: 0,
      payAmount: 0,
      totalAmount: 0
    }
  }
}
const onClickDiscounts = (row, record) => {
  if (!row.list || row.list.length <= 0) return message.error('请添加销售单商品内容')
  const flag = row.list?.some((i) => {
    return !i.id
  })
  if (flag) return message.error('请先保存销售单')
  if (record === 1) {
    discountsManyOpen.value = true
    projectItem.value = { ...row }
  } else {
    projectRow.value = { ...record, saleId: row.doSaveOoOpticianRecordRequest.id }
    discountsOneOpen.value = true
  }
}
//作废明细
const onDelete = async (record, fIdx, tIdx) => {
  if (record.isNew) {
    saleForm.value[fIdx].list.splice(tIdx, 1)
  } else {
    const { code, msg } = await post('/optometry/ooadolescentcheck/doModifyOoOpticianSubRecord', {
      id: record.id
    })
    if (code !== 0) return message.error(msg)
    message.success(msg)
    queryList()
  }
}
//删除销售单
const deleteCheckInfo = async (item, idx) => {
  if (saleForm.value[idx].isNew) {
    saleForm.value.splice(idx, 1)
  } else {
    const { code, msg } = await post('/optometry/ooadolescentcheck/doModifyOoOpticianRecord', {
      id: saleForm.value[idx].doSaveOoOpticianRecordRequest.id
    })
    if (code !== 0) return message.error(msg)
    message.success(msg)
    queryList()
  }
}
//右侧表格
const queryList = async () => {
  opticianStatus.value = false
  loading.value = true
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoOpticianRecordList', {
    ooLsh: selectedItem.value.jzbh,
    isXs: refundSwitch.value ? '' : '1', //是否显示退费  为空 显示  "1" 不显示
    status: ''
  })
  saveBtnLoading.value = false
  loading.value = false
  if (code !== 0) return message.error(msg)
  if (selectedItem.value.ysbh) {
    saleBankForm.value.doSaveOoOpticianRecordRequest.doctorId = selectedItem.value.ysbh
    saleBankForm.value.doSaveOoOpticianRecordRequest.doctorName = selectedItem.value.empName
  }
  if (data && data.length > 0) {
    saleForm.value = []
    data.forEach((item) => {
      if (item.ooOpticianRecordListResponse.status === '1') {
        //状态是否为已开单
        item.opticianStatus = true
        item.list.forEach((it) => {
          //状态是否为已缴费
          if (it.payStatus === '1') item.payStatus = true
        })
        opticianStatus.value = true
      } else {
        item.opticianStatus = false
      }
      if (item.list.length > 0) {
        item.list = item.list.map((it) => {
          return { mc: it.payItemName, gg: it.specification, ...it }
        })
      } else {
        item.list = JSON.parse(JSON.stringify(saleBankForm.value.list))
      }
      if (finialCheckInfo.value.isLong === '1' && finialCheckInfo.value.isShort === '1') {
        item.ooOpticianRecordListResponse.longShortDisabled = false
      } else if (finialCheckInfo.value.isLong === '1') {
        item.ooOpticianRecordListResponse.longShortDisabled = true
      } else if (finialCheckInfo.value.isShort === '1') {
        item.ooOpticianRecordListResponse.longShortDisabled = true
      } else {
        item.ooOpticianRecordListResponse.longShortDisabled = false
      }
      saleForm.value.push({
        downPayOpen: item.ooOpticianRecordListResponse.downPaymentAmount ? true : false,
        opticianStatus: item.opticianStatus,
        payStatus: item.payStatus,
        doSaveOoOpticianRecordRequest: item.ooOpticianRecordListResponse,
        list: item.list
      })
    })
  } else {
    saleForm.value = []
    AddSaleBill()
  }
  getPatientCouponList()
  setTimeout(function () {
    getMemberCardList()
  }, 200)
  getAmount()
}
const onBlurInput = (table, record) => {
  if (!table.isNew && !record.isNew) saveTableData(table)
}
const onBlurNum = (table, record, event) => {
  if (event.xmlbbh !== '63') {
    //角塑不检查sku/定制片不检查库存和sku
    //IS_CHECK_STORE_OWS  存的镜架镜片校验库存
    if (getSystemConfig('IS_CHECK_STORE_OWS') === '1' && record.isOutside === '0') {
      if (event.xmlbbh === '61') {
        if (event.storeType === '0') {
          if (event.target.value > record.stock) {
            message.error('数量超过最大库存量')
            record.num = record.stock
            return
          }
        }
      } else {
        if (event.target.value > record.stock) {
          message.error('数量超过最大库存量')
          record.num = record.stock
          return
        }
      }
    }
  }
  record.totalAmount = record.price * event.target.value
  record.payAmount = record.price * event.target.value
  if (!table.isNew && !record.isNew) saveTableData(table)
}
const NumChange = (table, record) => {
  record.totalAmount = record.price * record.num
  record.payAmount = record.price * record.num
  if (!table.isNew && !record.isNew) saveTableData(table)
}
const getSkuData = async (item, record, event, status, idx, index) => {
  //xmlbbh 镜架 60  设备 64  其他商品 65   镜片 61  隐形眼镜 62  角塑 63
  //eyesType   1  左眼 2  右眼 3  其他
  if (event.xmlbbh === '61' || event.xmlbbh === '62') {
    if (finialCheckInfo.value.isLong !== '1' && finialCheckInfo.value.isShort !== '1') {
      if (event.resolve) event.resolve(false)
      return message.warning('未生成最终处方')
    }
  }
  if ((record.eyesType === '1' || record.eyesType === '2') && item.doSaveOoOpticianRecordRequest.longOrShort <= 0) {
    if (event.resolve) event.resolve(false)
    return message.warning('请选择远用近用')
  }
  if (event.resolve) event.resolve(true)
  itemIdx.value = idx
  recordIdx.value = index
  if (event.xmlbbh !== '63') {
    //角塑不检查sku/定制片不检查库存和sku
    //IS_CHECK_STORE_OWS  存的镜架镜片校验库存
    if (getSystemConfig('IS_CHECK_STORE_OWS') === '1' && record.isOutside === '0') {
      if (event.xmlbbh === '61') {
        if (event.storeType === '0') {
          if (event.optimalInventory <= 0) {
            message.error('库存不足')
            event.mc = ''
            event.gg = ''
            return
          }
        }
      } else {
        if (event.optimalInventory <= 0) {
          message.error('库存不足')
          event.mc = ''
          event.gg = ''
          return
        }
      }
    }
  }
  record.skuId = event.skuid
  record.mc = event.mc
  record.payItemName = event.mc
  record.specification = event.gg
  record.gg = event.gg
  record.stock = event.optimalInventory
  record.availableStock = event.optimalInventory
  record.price = event.dj
  record.unit = event.dw
  record.astigmatism = event.astigmatism
  record.diopter = event.diopter
  record.payItemId = event.bh
  record.color = event.color
  record.modelNumber = event.modelNumber
  record.payItemType = event.xmlbbh
  record.storeType = event.storeType
  record.num = 1
  // 选中定制片和角膜塑形镜自动选中外购
  if (record.payItemType === '63' || (record.payItemType === '61' && event.storeType === '1') || getSystemConfig('IS_CHECK_STORE_OWS') !== '1') {
    record.isOutside = '1'
  }
  onBlurInput(item, record, event)
  NumChange(item, record)
  if (!saleForm.value[itemIdx.value]) return
  if (status) saleForm.value[itemIdx.value].list[recordIdx.value] = record
  saleForm.value[itemIdx.value].list[recordIdx.value].autoFocus = false
  // if (saleForm.value[itemIdx.value].list[recordIdx.value + 1] && saleForm.value[itemIdx.value].list[recordIdx.value + 1].isNew) {
  //   saleForm.value[itemIdx.value].list[recordIdx.value + 1].autoFocus = true
  // }
  const nextRecord = saleForm.value[itemIdx.value].list[recordIdx.value + 1]
  if (record.eyesType === '2' && nextRecord.eyesType === '1' && nextRecord.isNew) {
    const { code, data, msg } = await post('/optometry/ooadolescentcheck/getAnotherLens', {
      pageSize: '8',
      diopter: formatDiopter(item, nextRecord),
      astigmatism: formatAstigmatism(item, nextRecord),
      bh: event.bh,
      id: event.id
    })
    if (code !== 0) return message.error(msg || '查询失败')
    if (data && data.length > 0) {
      saleForm.value[itemIdx.value].list[recordIdx.value + 1].autoFocus = false
      getSkuData(item, saleForm.value[itemIdx.value].list[recordIdx.value + 1], data[0], false, itemIdx.value, index + 1)
    } else {
      if (saleForm.value[itemIdx.value].list[recordIdx.value + 1] && saleForm.value[itemIdx.value].list[recordIdx.value + 1].isNew) {
        saleForm.value[itemIdx.value].list[recordIdx.value + 1].autoFocus = true
      }
    }
  } else {
    if (saleForm.value[itemIdx.value].list[recordIdx.value + 1] && saleForm.value[itemIdx.value].list[recordIdx.value + 1].isNew) {
      saleForm.value[itemIdx.value].list[recordIdx.value + 1].autoFocus = true
    }
  }
}
//是否外购change
const onSwitchChange = async (e, record, item) => {
  if (record.isNew || item.opticianStatus) return
  const { code, msg } = await post('/optometry/ooadolescentcheck/doModifyIsOutSide', {
    id: record.id,
    isOutside: e.toString()
  })
  if (code !== 0) return message.error(msg || '修改失败')
  message.success(msg)
}

const onSuccessCoupon = async (e, item) => {
  item.doSaveOoOpticianRecordRequest.couponsNo = e.dyq?.id
  item.doSaveOoOpticianRecordRequest.vipNo = e.vip?.cardno
  if (!item.isNew) {
    const { code, msg } = await post('/optometry/ooadolescentcheck/doHykDiscount', {
      couponsNo: e.dyq?.id,
      dyqje: e.dyq?.offsetAmount,
      hyxmlb: e.vip?.hyxmlb,
      vipNo: e.vip?.cardno,
      yhfs: e.yhfs,
      id: item.doSaveOoOpticianRecordRequest.id,
      ooLsh: selectedItem.value.jzbh
    })
    if (code !== 0) return message.error(msg || '操作失败')
    queryList()
    // getAmount()
  }
}
//获取最终处方数据
const getFinalCheckInfo = async (flag) => {
  preLoading.value = true
  const { code, data, msg } = await post('/optometry/ooadolescentcheck/getOoFinalCheckInfo', {
    ooLsh: selectedItem.value.jzbh
  })
  preLoading.value = false
  finialCheckInfo.value = {}
  if (code !== 0) return message.error(msg || '查询失败')
  finialCheckInfo.value = data || {}
  if (finialCheckInfo.value.isLong === '1' && finialCheckInfo.value.isShort === '1') {
    saleBankForm.value.doSaveOoOpticianRecordRequest.longOrShort = ''
    saleBankForm.value.doSaveOoOpticianRecordRequest.longShortDisabled = false
  } else if (finialCheckInfo.value.isLong === '1') {
    saleBankForm.value.doSaveOoOpticianRecordRequest.longOrShort = '1'
    saleBankForm.value.doSaveOoOpticianRecordRequest.longShortDisabled = true
  } else if (finialCheckInfo.value.isShort === '1') {
    saleBankForm.value.doSaveOoOpticianRecordRequest.longOrShort = '2'
    saleBankForm.value.doSaveOoOpticianRecordRequest.longShortDisabled = true
  } else {
    saleBankForm.value.doSaveOoOpticianRecordRequest.longOrShort = ''
    saleBankForm.value.doSaveOoOpticianRecordRequest.longShortDisabled = false
  }
  // 页面样式为收缩样式时才会调用
  if (pageOne.value !== '0') {
    timer.value = setTimeout(() => {
      isShowPreTable.value = false
    }, 3000)
  }
  if (flag) queryList()
}
const AddTableItem = (item) => {
  item.list.push({
    isNew: true,
    eyesType: '',
    payItemType: '65',
    payStatus: '0',
    isOutside: '0',
    adviceTime: dayjs().format('YYYY-MM-DD hh:mm:ss')
  })
}
const AddSaleBill = async () => {
  const { code, msg, data } = await post('/optometry/ooadolescentcheck/doSveGenerateSalesOrders', {})
  if (code !== 0) return message.error(msg || '操作失败')
  const saleBank = JSON.parse(JSON.stringify(saleBankForm.value))
  saleBank.doSaveOoOpticianRecordRequest.id = data.id
  saleForm.value.push(saleBank)
}
const onLongShortChange = (e, item) => {
  const arr = item.list.filter((it) => it.payItemId)
  if (arr && arr.length > 0) {
    Modal.confirm({
      title: '提示',
      icon: createVNode(ExclamationCircleOutlined),
      content: '切换将会清空销售单内容，是否继续？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        item.doSaveOoOpticianRecordRequest.longOrShort = e.target.value
        const ids = item.list.filter((it) => it.id)
        if (ids && ids.length > 0) {
          ids.forEach(async (it, idx) => {
            const { code, msg } = await post('/optometry/ooadolescentcheck/doModifyOoOpticianSubRecord', {
              id: it.id
            })
            if (code !== 0) return message.error(msg)
            message.success(msg)
            if (idx === ids.length - 1) queryList()
          })
        } else {
          item.list = JSON.parse(JSON.stringify(saleBankForm.value.list))
        }
      }
    })
  } else {
    item.doSaveOoOpticianRecordRequest.longOrShort = e.target.value
  }
}
const printSale = async (row) => {
  if (row.list.length <= 0) return message.error('请先添加销售单')
  const flag = row.list.some((it) => {
    return it.isNew
  })
  if (flag) return message.error('请先保存销售单')
  const { code, msg, data } = await post('/optometry/ooadolescentcheck/getPrintOoOpticianRecord', {
    xsdh: row.doSaveOoOpticianRecordRequest.id
  })
  if (code !== 0) return message.error(msg || '打印失败')
  window.openExe?.rpt(data) //调用winform打印
}
const downPaySwitchChange = (e, item) => {
  if (!e) {
    item.doSaveOoOpticianRecordRequest.downPaymentAmount = 0
    if (!item.isNew) saveTableData(item)
  }
}
const itemIdx = ref(0)
const recordIdx = ref(0)
const openSearchModal = (item, record, idx, index) => {
  formItem.value = item
  if (record.payItemType === '60') {
    glassesFrameSearch.value = true
  } else if (record.payItemType === '61' || record.payItemType === '62' || record.payItemType === '63') {
    // if (finialCheckInfo.value.isLong !== '1' && finialCheckInfo.value.isShort !== '1') {
    //   return message.error('未生成最终处方')
    // } else {
    //   if (item.doSaveOoOpticianRecordRequest.longOrShort <= 0) {
    //     return message.error('请选择远用近用')
    //   }
    // }
    // formItem.value.astigmatism = formatAstigmatism(item, record)
    // formItem.value.diopter = formatDiopter(item, record)
    LensSearch.value = true
  } else {
    OtherSearch.value = true
  }
  recordItem.value = record
  itemIdx.value = idx
  recordIdx.value = index
}
const onSelectSearch = (record) => {
  getSkuData(formItem.value, recordItem.value, record, true)
}
const tranPreTable = (val) => {
  isShowPreTable.value = val
}
const tranEditEmp = () => {
  if (opticianStatus.value) return message.warning('已开单禁止修改')
  isEditChkEmpId.value = true
  isShowPreTable.value = true
  if (timer.value) clearTimeout(timer.value)
}
const tranEditTime = () => {
  if (opticianStatus.value) return message.warning('已开单禁止修改')
  isEditChkTime.value = true
  isShowPreTable.value = true
  if (!finialCheckInfo.value.updateTime) finialCheckInfo.value.updateTime = null
  if (timer.value) clearTimeout(timer.value)
}
const tranEditPreTable = () => {
  if (!store.currentPatient.brId) return message.warning('请先先选择患者')
  if (opticianStatus.value) return message.warning('已开单禁止修改')
  isEditPreTable.value = true
  isShowPreTable.value = true
  if (timer.value) clearTimeout(timer.value)
}
const onConfirmEditPre = () => {
  preTable.value.sendData()
}
const onConfirmEditPreTime = () => {
  preTable.value.sendData()
}
const onSuccessPreTable = (e) => {
  onSavePreTable({ ...e, chkEmpId: finialCheckInfo.value.chkEmpId, updateTime: finialCheckInfo.value.updateTime }, 1)
}
const onSavePreTable = async (e, type) => {
  const { code, msg } = await post('/optometry/ooadolescentcheck/doSaveOoFinalCheckSG', {
    ...e,
    type,
    brId: store.currentPatient.brId,
    ooLsh: store.currentPatient.jzbh
  })
  // getFinalCheckInfo(true)
  if (code !== 0) return message.error(msg || '保存失败')
  message.success(msg || '保存成功')
  getFinalCheckInfo(true)
  isEditPreTable.value = false
  isEditChkEmpId.value = false
}
const ticketData = ref([])
// 优惠卷
const getPatientCouponList = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getPatientCouponList', {
    brId: store.currentPatient.brId,
    status: '0',
    pyjm: ''
  })
  if (code !== 0) return message.error(msg)
  ticketData.value = data
}
const vipCardData = ref([])
// 会员卡
const getMemberCardList = async () => {
  const { code, data, msg } = await post('/outp/oupCharge/getMemberCardSG', {
    brId: store.currentPatient.brId
  })
  if (code !== 0) return message.error(msg)
  if (data) {
    vipCardData.value = data || []
  }
}
const onBlurInputDownPay = (item) => {
  if (!item.isNew) saveTableData(item)
}
const getRowClass = (record) => {
  const className = {
    'table-row-new': record.isNew
  }
  return Object.keys(className)
    .filter((key) => className[key])
    .join(' ')
}
const judgeSelect = (item) => {
  if (item.doSaveOoOpticianRecordRequest.longOrShort <= 0) {
    return false
  } else {
    return true
  }
}
const onJudgeFocus = (item) => {
  if (item.doSaveOoOpticianRecordRequest.longOrShort <= 0) {
    message.warning('请选择远用近用')
  }
}
const formatAstigmatism = (item, record) => {
  let astigmatism = ''
  if (record.eyesType === '2') {
    //右眼
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '1') {
      astigmatism = finialCheckInfo.value.odLongCyl
    }
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '2') {
      astigmatism = finialCheckInfo.value.odShortCyl
    }
  } else if (record.eyesType === '1') {
    //左眼
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '1') {
      astigmatism = finialCheckInfo.value.osLongCyl
    }
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '2') {
      astigmatism = finialCheckInfo.value.osShortCyl
    }
  } else {
    //其他
    astigmatism = ''
  }
  if (astigmatism) {
    astigmatism = astigmatism.replace('+', '')
    return astigmatism
  } else {
    return astigmatism
  }
}
const formatDiopter = (item, record) => {
  let diopter = ''
  if (record.eyesType === '2') {
    //右眼
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '1') {
      diopter = finialCheckInfo.value.odLongSph
    }
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '2') {
      diopter = finialCheckInfo.value.odShortSph
    }
  } else if (record.eyesType === '1') {
    //左眼
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '1') {
      diopter = finialCheckInfo.value.osLongSph
    }
    if (item.doSaveOoOpticianRecordRequest.longOrShort === '2') {
      diopter = finialCheckInfo.value.osShortSph
    }
  } else {
    //其他
    diopter = ''
  }
  if (diopter) {
    diopter = diopter.replace('+', '')
    return diopter
  } else {
    return diopter
  }
}
const formatLb = (val) => {
  if (val === '60') {
    return ['60']
  } else if (val === '61' || val === '62' || val === '63') {
    return ['61', '62', '63']
  } else {
    return ['64', '65']
  }
}
watch(
  () => store.currentPatient.jzbh,
  (val) => {
    if (val) {
      isShowPreTable.value = true
      selectedItem.value = store.currentPatient
      saleForm.value = []
      amountNum.value = {
        discountAmount: 0,
        payAmount: 0,
        totalAmount: 0
      }
      getFinalCheckInfo(true)
    }
  }
)
const refundSwitch = ref(false)
watch(
  () => store.refundSwitch,
  (val) => {
    refundSwitch.value = val
    store.currentPatient.brId && queryList()
  },
  { immediate: true }
)
onMounted(() => {
  pageOne.value = getSystemConfig('OOS_OPTICAN_MODE') //页面样式  0:默认样式|1：收缩样式
  // prescriptionMode.value = getSystemConfig('OOS_OPTICIAN_FINAL_PRESCRIPTION_SHOW_MODE') //最终处方展示样式 0：永久显示|1:3秒自动缩小
})
onUnmounted(() => {
  if (timer.value) clearTimeout(timer.value)
  timer.value = null
})
</script>

<style lang="less" scoped>
.radio-style {
  :deep(.ant-radio-button-wrapper) {
    width: 66.4%;
    padding: 0;
    text-align: center;
  }
}

.title {
  position: relative;
  width: 100%;
  margin-bottom: 8px;
  padding-left: 16px;
  font-weight: 600;

  &::after {
    position: absolute;
    top: calc(50% - 8px);
    left: 0;
    width: 4px;
    height: 16px;
    background-color: var(--primary-color);
    content: '';
  }
}
.form-header {
  background-color: #f2f2f2;
}
@media screen and (max-width: 1200px) {
  .form-header {
    flex-direction: column !important;
    align-items: flex-start;
    .form-style-flex {
      margin-left: 16px;
    }
    .ant-form-item {
      width: 30%;
      margin-top: 8px;
      margin-left: 8px;
    }
    .btn-box {
      margin-top: 16px;
    }
  }
}
:deep(.table-wrap > .ant-card) {
  border-radius: 0px 0px 4px 4px;
}
</style>
